﻿using Common.Dtos;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using Sigma.Admin.Client.DialogAware;
using Sigma.Admin.Client.Events;
using Sigma.Admin.Client.Extensions;
using Sigma.Admin.Client.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sigma.Admin.Client.ViewModels
{
    [RegionMemberLifetime(KeepAlive = false)]
    public class UsersViewModel:NavigationViewModel
    {
        private readonly IUserService _userService;
        private readonly IDialogHostService _dialog;
        private readonly IRegionManager _regionManager;
        private readonly SubscriptionToken _token;
        public UsersViewModel(IRegionManager regionManager,IEventAggregator ea, IContainerProvider containerProvider,IUserService service, IDialogHostService dialog) : base(ea, containerProvider)
        {
            _userService = service;
            ExecuteCommand = new DelegateCommand<string>(Execute);
            _dialog=dialog;
            _token = _ea.ResgiterMessage(EditOrCancel,"UserVM");
            _regionManager=regionManager;
        }

        #region datagrid相关属性
        private bool _isAllSelect;

        public bool IsAllSelect
        {
            get { return _isAllSelect; }
            set { _isAllSelect = value;
                RaisePropertyChanged();
                if (_isAllSelect)
                    UserItems.ForEach(x => x.IsCheck = true);
                else
                    UserItems.ForEach(x => x.IsCheck = false);
                }
        }
        #endregion

        #region 呈现数据集
        private List<UsersDto> _userItems;

        public List<UsersDto> UserItems
        {
            get { return _userItems; }
            set { _userItems = value; RaisePropertyChanged(); }
        }
        #endregion

        #region 备份数据集
        public List<UsersDto> BackUsers { get; set; }
        //深度拷贝
        private void BackUpAllUsers()
        {
            var back = JsonConvert.SerializeObject(_userItems);
            BackUsers = JsonConvert.DeserializeObject<List<UsersDto>>(back);
        }

        private void ReturnBackUp()
        {
            if(BackUsers.Count()==0)
                return;
            UserItems = BackUsers.ToList();
            BackUsers.Clear();
        }
        #endregion

        #region 是否可选、可编辑控制
        private bool _isEnadle=true;
        //时候可选默认ture ，处于编辑状态时为false，要注意给readonly属性绑定要取反
        public bool IsEnable
        {
            get { return _isEnadle; }
            set { _isEnadle = value;RaisePropertyChanged(); }
        }

        //private bool _isEditable;

        //public bool IsEditable
        //{
        //    get { return _isEditable; }
        //    set { _isEditable = value; }
        //}
        //改变选中数据的可编辑状态
        private void ChangeEditable()
        {
            _userItems.Where(x => x.IsCheck).ToList().ForEach(x=>x.IsReadOnly= !x.IsReadOnly);
        }

        #endregion

        #region 初始化获取数据
        async Task GetDataAsync()
        {
            UpdateLoading(true);

            var res = await _userService.GetAllUser();
            
            if (res.Status)
            {
                UserItems = res.Result;
            }
            else
            {
                _ea.SendMessage(res.Message);
            }
            UpdateLoading(false);
        }

        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);

            await GetDataAsync();
        }
        #endregion

        public DelegateCommand<string> ExecuteCommand { get; private set; }

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "AddUser":
                    AddUser();break;
                case "SaveChange":
                    SaveChange();break;
                case "Delete":
                    Delete();break;

            }
        }

        private async void Delete()
        {
            var checks = _userItems.Where(x => x.IsCheck).ToList();
            if (checks.Count == 0)
            {
                _ea.SendMessage("请选择要删除的数据");
                return;
            }

            var res = await _userService.DeleteUsers(checks);
            if (res.Status)
            {
                _ea.SendMessage(res.Message);
                await GetDataAsync();
            }else
                _ea.SendMessage(res.Message);
        }

        #region 添加用户
        public async Task AddUser()
        {
            DialogParameters param = new DialogParameters();
            var dialogResult = await _dialog.ShowDialog("AddUserView",param);
            //添加角色后刷新
            if(dialogResult.Result==ButtonResult.OK)
                await GetDataAsync();
        }
        #endregion

        #region 修改、取消修改、保存用户
        private void EditOrCancel(MessageModel mm)
        {
            switch (mm.Message)
            {
                case "Edit":
                    ExcuteEdit(); break;
                case "Cancel":
                    ExcuteCancel(); break;
            }
        }
        //开启编辑
        private void ExcuteEdit()
        {
            BackUpAllUsers();
            IsEnable = false;//关闭按钮和checkbox
            ChangeEditable();//开启选中数据编辑
            

        }
        //取消编辑
        private void ExcuteCancel()
        {
            IsEnable=true;
            //ChangeEditable();
            ReturnBackUp();
        }

        private async void SaveChange()
        {
            var checks = _userItems.Where(x => x.IsCheck).ToList();
            if (checks.Count == 0)
            {
                _ea.SendMessage("请先取消再选择要修改的数据");
                return;
            }
                
            var res = await _userService.UpdateUsers(checks);
            if (res.Status)
            {
                var param = new NavigationParameters();
                param.Add("doNotCreate", false);
                UpdateLoading(true);
                _ea.UnResgiterMessage(_token);//解绑数据
                _regionManager.RequestNavigate("ContentRegion", "UsersView", param);
            }
            else
            {
                _ea.SendMessage("保存失败："+res.Message);
            }
            
            
        }

        
        #endregion


    }
}
